package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: HotArticleServiceImpl
 * Description:
 * date: 2023/8/26 0026 19:19
 *
 * @author zHan
 */
@Service
@Slf4j
@Transactional
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        // 查询前5天的文章数据
        Date last5Date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticleList = apArticleMapper.findArticlesLast5Days(last5Date);
        // 计算文章分值
        List<HotArticleVo> hotArticleVoList = computeHotArticleWithScore(apArticleList);
        // 为每个频道缓存30条分值较高的文章
        cacheHotArticleToRedis(hotArticleVoList);
    }

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 为每个频道缓存30条分值较高的文章
     *
     * @param hotArticleVoList
     */
    private void cacheHotArticleToRedis(List<HotArticleVo> hotArticleVoList) {
        // 为每个频道缓存30条分值较高的文章
        ResponseResult responseResult = wemediaClient.getChannels();
        if (responseResult.getCode().equals(200)) {
            String jsonChannels = JSON.toJSONString(responseResult.getData());
            System.out.println(jsonChannels);
            List<WmChannel> wmChannelList = JSON.parseArray(jsonChannels, WmChannel.class);
            // 检索出每个频道的文章
            if (wmChannelList != null && wmChannelList.size() > 0) {
                for (WmChannel wmChannel : wmChannelList) {
                    List<HotArticleVo> hotArticleVos =
                            hotArticleVoList.stream()
                                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(wmChannel.getId()))
                                    .collect(Collectors.toList());
                    // 对每个频道缓存30条分值较高的文章进行排序和缓存
                    sortAndCache(hotArticleVos,
                            ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
        // 推荐数据
        sortAndCache(hotArticleVoList,
                ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 对热点文章进行排序和缓存
     *
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .collect(Collectors.toList());
        // 给文章排序，取30条分值较高的文章存入reidis    key：channelId，value：hotArticleVos
        if (hotArticleVos.size() > 30) {
            hotArticleVos = hotArticleVos.subList(0, 30);
        }
        // 存入redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章分值
     *
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeHotArticleWithScore(List<ApArticle> apArticleList) {
        List<HotArticleVo> hotArticleVoList = null;
        if (apArticleList != null && apArticleList.size() > 0) {
            hotArticleVoList = apArticleList.stream().map(apArticle -> {
                // 创建vo对象
                HotArticleVo hotArticleVo = new HotArticleVo();
                // 对象拷贝
                BeanUtils.copyProperties(apArticle, hotArticleVo);
                // 计算分值
                Integer score = getScore(apArticle);
                hotArticleVo.setScore(score);
                return hotArticleVo;
            }).collect(Collectors.toList());
        }
        return hotArticleVoList;
    }

    /**
     * 计算分值
     *
     * @param apArticle
     * @return
     */
    private Integer getScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
